package com.yorkfeng.blemulti.Activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.yorkfeng.blemulti.Adapter.BAdapter;
import com.yorkfeng.blemulti.R;
import com.yorkfeng.blemulti.Utils.Constants;
import com.yorkfeng.blemulti.Utils.CustomToast;

import java.util.ArrayList;

public class BluetoothSearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private final static String TAG = BluetoothSearchActivity.class.getSimpleName();

    private BluetoothAdapter mBA;

    private BAdapter bleAdapter = null;
    private ArrayList<BluetoothDevice> arraySource = null;

    private ListView listdevicefound;

    protected boolean btSearching = false;
    protected boolean refused = false;

    private int gatt;

    // 5秒后停止查找搜索.
    private static final long SCAN_PERIOD = 5000;

    private static final int REQUEST_ENABLE_BT = 1;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_search);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        gatt = bundle.getInt("GATT");

        getSupportActionBar().setTitle("SCAN");

        mHandler = new Handler();

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBA = bluetoothManager.getAdapter();

        listdevicefound = (ListView) findViewById(R.id.devicefound);
        listdevicefound.setOnItemClickListener(this);

        arraySource = new ArrayList<BluetoothDevice>();
        bleAdapter = new BAdapter(this, arraySource);

        listdevicefound.setAdapter(bleAdapter);
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!arraySource.contains(device)) {
                        arraySource.add(device);
                    }
                    bleAdapter.notifyDataSetChanged();
                }
            });
        }
    };

    private void scanLeDevice(final boolean enable) {
        // 蓝牙未打开
        if (!mBA.isEnabled()) {
            return;
        }

        if (enable) {
            // Stops scanning after a pre-defined scan period.
            // 使用PostDelayed方法，SCAN_PERIOD后调用此Runnable对象
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    btSearching = false;
                    mBA.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            btSearching = true;
            mBA.startLeScan(mLeScanCallback);
        } else {
            btSearching = false;
            mBA.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }

    private void refresh() {
        if (!mBA.isEnabled() && !refused) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        if (refused) {
            refused = false;
        }

        arraySource = new ArrayList<BluetoothDevice>();
        bleAdapter = new BAdapter(this, arraySource);

        listdevicefound.setAdapter(bleAdapter);

        scanLeDevice(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 用户没有拒绝打开蓝牙
        if (!mBA.isEnabled() && !refused) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        if (refused) {
            refused = false;
        }

        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        arraySource.clear();
        bleAdapter.notifyDataSetChanged();
        if (btSearching) {
            scanLeDevice(false);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scan, menu);
        //返回true才会显示overflow按钮
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.action_scan:
                refresh();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // User chose not to enable Bluetooth.
                // 用户选择不开启蓝牙 弹出
                if (resultCode == Activity.RESULT_CANCELED) {
                    // Toast.makeText(BluetoothSearchActivity.this,
                    // getResources().getString(R.string.please_activate_bt),
                    // Toast.LENGTH_SHORT).show();

                    CustomToast.showToast(getBaseContext(), "Please activate Bluetooth.", 1000);
                    refused = true;
                    Log.d(TAG, "拒绝打开蓝牙");
                    return;
                } else if (resultCode == Activity.RESULT_OK) {
                    Log.d(TAG, "打开蓝牙");

                    return;
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        BluetoothDevice device = arraySource.get(arg2);
        if (device == null) {
            return;
        }

        // 保存最后连接的设备地址
        SharedPreferences pres = BluetoothSearchActivity.this.getSharedPreferences(Constants.CONFIG_FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pres.edit();
        if (gatt == 0) {
            editor.putString(Constants.LAST_CONNECTED_ADDRESS_L, device.getAddress());
        }else if (gatt == 1) {
            editor.putString(Constants.LAST_CONNECTED_ADDRESS_R, device.getAddress());
        }

        // 不存在这个设备，存入文件名
        if (pres.getString(device.getAddress(), "").length() == 0) {
            editor.putString(device.getAddress(), device.getName());
        }
        editor.commit();

        if (btSearching) {
            mBA.stopLeScan(mLeScanCallback);
            btSearching = false;
        }

        finish();
    }
}
